package org.msb.accentis.data;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Database {

	private static final String ENCRYPTED_MARKER_FILENAME = ".encrypted"; //$NON-NLS-1$

	private String databaseLocation;

	private IDataManager dataManager;

	Database(IDataManager dm, boolean encrypted, String location) {
		dataManager = dm;
		databaseLocation = location;
		ensureMarkerFilePresence(encrypted);
	}

	public boolean isEncrypted() {
		return isDatabaseLocationEncrypted(getLocation());
	}

	public void setEncrypted(boolean value) {
		ensureMarkerFilePresence(value);
	}

	public String getLocation() {
		return databaseLocation;
	}

	public IDataManager getDataManager() {
		return dataManager;
	}

	private void ensureMarkerFilePresence(boolean encrypted) {
		File markerFile = new File(getLocation(), ENCRYPTED_MARKER_FILENAME);

		if (markerFile.exists() && !encrypted)
			markerFile.delete();
		else if (!markerFile.exists() && encrypted)
			createMarkerFile(markerFile);
	}

	private void createMarkerFile(File file) {
		try {
			file.mkdirs();
			file.createNewFile();
		} catch (IOException ex) {
			Logger.getLogger("accentis", "org.msb.accentis.data.resources").log(Level.WARNING, "messages.cantcreateencryptedmarkerfile", file); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
		}
	}

	public static boolean isDatabaseLocationEncrypted(String location) {
		File markerFile = new File(location, ENCRYPTED_MARKER_FILENAME);

		return markerFile.exists();
	}
}
